IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cms_sp_PageAdd]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[cms_sp_PageAdd]
GO
create procedure [dbo].[cms_sp_PageAdd]
(
@PageId [int] = null output,
@SiteGroupId int = null,
@SiteId int = null,
@SystemLanguageId int = null,
@TemplateId int,
@WorkflowId uniqueidentifier = null,
@IsLatestCompletedRevision bit,
@ParentPageId int = null,
@PageTypeKey int,
@PageBehaviourTypeKey int,
@PageName nvarchar(150),
@PageUrl nvarchar(250),
@IsVisible bit,
@UseFileCache bit,
@IsPublished bit = null,
@CreatedBy int,
@DateCreated datetime,
@PageTypeParameter nvarchar(150),
@PublishStartDate datetime = null,
@PublishEndDate datetime = null
)
as
declare @PageNodeId hierarchyid
declare @IsLatestRevision bit 
declare @IsDeleted bit
if @IsPublished is null
begin
	set @IsPublished = 1
end
set @IsDeleted = 0
set @IsLatestRevision = 1
if @ParentPageId is null
begin
	set @PageNodeId = hierarchyid::GetRoot()
end
else
begin
	declare @ParentPageNodeId hierarchyid
	declare @NodeId hierarchyid
	select @ParentPageNodeId = PageNodeId from dbo.Pages
	where PageId = @ParentPageId
	select @NodeId = max(PageNodeId) from dbo.Pages
	where PageNodeId.GetAncestor(1) = @ParentPageNodeId
	set @PageNodeId = @ParentPageNodeId.GetDescendant(@NodeId, NULL)
end
insert into dbo.Pages
(
SiteGroupId,
SiteId,
SystemLanguageId,
TemplateId,
PageNodeId,
PublicPageId,
PageTypeKey,
PageBehaviourTypeKey,
PageName,
PageUrl,
IsVisible,
UseFileCache,
CreatedBy,
DateCreated
)
values
(
@SiteGroupId,
@SiteId,
@SystemLanguageId,
@TemplateId,
@PageNodeId,
0,
@PageTypeKey,
@PageBehaviourTypeKey,
@PageName,
@PageUrl,
@IsVisible,
@UseFileCache,
@CreatedBy,
@DateCreated
)
set @PageId = SCOPE_IDENTITY()
update dbo.Pages
	set PublicPageId = @PageId
where PageId = @PageId
insert into dbo.EntityRevisions
(
EntityId,
PublicEntityId,
EntityTypeParameter,
WorkflowId,
IsLatestRevision,
IsLatestCompletedRevision,
IsDeleted,
IsPublished,
PublishStartDate,
PublishEndDate
)
values
(
@PageId,
@PageId,
@PageTypeParameter,
null,
@IsLatestRevision,
@IsLatestCompletedRevision,
@IsDeleted,
@IsPublished,
@PublishStartDate,
@PublishEndDate
)
return @PageId
GO